/**
 * tjftp -- A simple FTP server, using the ANSI C
 * Copyright (C) 2011  degui.chen <degui.chen@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "log.h"
#include <sys/stat.h>
#include <stdlib.h>
#include <pthread.h>
static FILE *log_fp;
int tj_log_open(PSettings settings) {
	if ((log_fp = fopen(settings->log_file, "a+")) == NULL) {
		perror("fopen");
		return -1;
	}
	fseek(log_fp, 0, SEEK_END);
	return 0;
}
void tj_log_close() {
	if (NULL != log_fp) {
		fflush(log_fp);
		fclose(log_fp);
	}
}
static _get_time(char* timE) {
	time_t rawtime;
	struct tm * timeinfo;
	time(&rawtime);
	timeinfo = localtime(&rawtime);
	strftime(timE, 80, "%Y-%m-%d %I:%M:%S", timeinfo);
}

static pthread_mutex_t mutex_log = PTHREAD_MUTEX_INITIALIZER;
static void* _log_thread_function(void *parameter) {
	pthread_mutex_lock(&mutex_log);
	pthread_detach(pthread_self());
	char *message = (char *) parameter;
	char time[80] = "";
	_get_time(time);
	char result[256] = { '\0' };
	sprintf(result, "%s	uid:[%i]	pid:[%i]	tid:[%u]	%s \n", time, getuid(), getpid(), pthread_self(), message);
	fputs(result, log_fp);
	pthread_mutex_unlock(&mutex_log);
}

void tj_log_write(char* message) {
	pthread_t thread_id;
	pthread_create(&thread_id, NULL, _log_thread_function, message);
}
